package com.transpot.controller.driver;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.transpot.entry.car.Car;
import com.transpot.entry.car.CarDriver;
import com.transpot.entry.driver.Driver;
import com.transpot.entry.driver.DriverPicture;
import com.transpot.entry.driver.DriverVO;
import com.transpot.entry.driver.Picture;
import com.transpot.service.car.CarDriverService;
import com.transpot.service.car.CarService;
import com.transpot.service.driver.DriverPictureService;
import com.transpot.service.driver.DriverService;
import com.transpot.service.driver.PictureService;
import com.transpot.utils.R;
import com.transpot.utils.UploadUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@RequestMapping("/driver")
public class DriverController {
    @Autowired
    private CarService carService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private PictureService pictureService;
    @Autowired
    private DriverPictureService driverPictureService;
    @Autowired
    private CarDriverService carDriverService;

    /**
     * 注册司机方法（司机可带车入职）
     * @param driverJSON
     * @param carJSON
     * @param file1
     * @param file2
     * @param file3
     * @param file4
     * @param file5
     * @return
     */
    @PostMapping("/registerDriverAndCar")
    public R registerDriverAndCar(@RequestParam("driver") String driverJSON, @RequestParam("car") String carJSON,
                            @RequestParam("file1") MultipartFile file1,
                            @RequestParam("file2") MultipartFile file2,
                            @RequestParam("file3") MultipartFile file3,
                            @RequestParam("file4") MultipartFile file4,
                            @RequestParam("file5") MultipartFile file5) {
        //创建json转化对象
        ObjectMapper mapper = new ObjectMapper();
        //把json字符串转换成对象
        Car car = null;
        Driver driver = null;
        try {
            driver = mapper.readValue(driverJSON, Driver.class);
            car = mapper.readValue(carJSON, Car.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //设置账号角色为司机
        driver.setRole(1);
        //调用driverService层方法注册司机信息
        driverService.registerDriver(driver);
        //调用carService层方法注册车辆信息
        //如果存在车辆信息则添加
        if (StringUtils.isNotBlank(car.getNumber()) && StringUtils.isNotBlank(car.getEngineNo())
                && StringUtils.isNotBlank(car.getCreationTime().toString()))
            carService.registerCar(car);
        //创建存放图片路径的对象
        Picture picture = new Picture();
        //调用图片上传方法上传图片
        if (!file1.isEmpty()) {
            //调用方法将图片上传，得到图片返回路径
            String imgUrl1 = UploadUtil.uploadImg(file1);
            //将图片路径存入图片信息对象中
            picture.setImgUrl1(imgUrl1);
        }
        if (!file2.isEmpty()) {
            String imgUrl2 = UploadUtil.uploadImg(file2);
            picture.setImgUrl2(imgUrl2);
        }
        if (!file3.isEmpty()) {
            String imgUrl3 = UploadUtil.uploadImg(file3);
            picture.setImgUrl3(imgUrl3);
        }
        if (!file4.isEmpty()) {
            String imgUrl4 = UploadUtil.uploadImg(file4);
            picture.setImgUrl4(imgUrl4);
        }
        if (!file5.isEmpty()) {
            String imgUrl5 = UploadUtil.uploadImg(file5);
            picture.setImgUrl5(imgUrl5);
        }
        //调用MP的原生方法保存picture对象
        pictureService.save(picture);
        //创建照片司机中间表对象
        DriverPicture driverPicture = new DriverPicture();
        //设置图片主键
        driverPicture.setPictureId(picture.getId());
        //设置司机主键
        driverPicture.setDriverId(driver.getId());
        //调用原生MP方法保存司机和图片的中间对象
        driverPictureService.save(driverPicture);
        //创建司机和汽车中间表对象
        //如果存在汽车ID和司机ID
        if (car.getId() != null && driver.getId() != null) {
            CarDriver carDriver = new CarDriver();
            //设置司机主键
            carDriver.setDriverId(driver.getId());
            //设置汽车主键
            carDriver.setCarId(car.getId());
            //调用原生MP方法保存汽车司机的中间对象
            carDriverService.save(carDriver);
        }
        return R.success();
    }

    /**
     * 根据分页的当前页码，分页大小，司机姓名条件，驾照类型条件分页返回信息的方法接口
     * @param current
     * @param size
     * @param name
     * @param type
     * @return
     */
    @GetMapping("/getDriverByConditionAndPage")
    public R getDriverByConditionAndPage(int current, int size, String name, String type) {
        //创建条件查询对象
        LambdaQueryWrapper<Driver> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //当用户输入姓名作为查询条件时，添加该条件
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(name), Driver::getName, name);
        //当用户输入证件类型作为查询条件时，添加该条件
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(type), Driver::getType, type);
        //创建分页查询对象
        IPage<Driver> driverIPage = new Page<>(current, size);
        //调用mp的分页查询方法得到司机的信息
        driverService.page(driverIPage, lambdaQueryWrapper);
        //把得到的分页司机信息传到service层处理数据，并返回DriverVO类型的分页对象
        Page<DriverVO> driverVOPage = driverService.getDriverVO(driverIPage);
        //把结果返回给前端
        return R.success(driverVOPage);
    }

    /**
     * 根据司机的id删除司机方法接口
     * @param id
     * @return
     */
    @DeleteMapping("/deleteDriverById")
    public R deleteDriverById(Integer id) {
        //调用service层方法删除司机
        driverService.deleteDriverById(id);
        return R.success();
    }

    /**
     * 更新司机信息方法接口(改变图片信息)
     * @param driverJson
     * @param
     * @param carList
     * @param
     * @return
     */
    @PostMapping("/updateDriverAll")
    public R updateDriverAll(@RequestParam("drivers") String driverJson, @RequestParam("imgs") String imgJson,
                          @RequestParam("file[]") MultipartFile[] files, @RequestParam("cars") String carList) {
        driverService.updateDriverAll(driverJson, imgJson, files, carList);
        return R.success();
    }
    /**
     * 更新司机信息方法接口(未改变图片信息)
     * @param driverJson
     * @param carList
     * @return
     */
    @PostMapping("/updateDriver")
    public R updateDriver(@RequestParam("drivers") String driverJson, @RequestParam("cars") String carList) {
        driverService.updateDriver(driverJson, carList);
        return R.success();
    }

    /**
     * 获取全部司机信息
     * @return
     */
    @GetMapping("/getAllDriver")
    public R getAllDriver() {
        List<Driver> driverList = driverService.list();
        return R.success(driverList);
    }

    /**
     * 修改司机的个人信息
     * @param driver
     * @return
     */
    @PostMapping("/updateDriverBase")
    public R updateDriverBase(@RequestBody Driver driver) {
        //设置最后一次修改时间为当前
        driver.setUpdateTime(LocalDateTime.now());
        //调用mp的原生方法修改司机信息
        driverService.updateById(driver);
        return R.success();
    }
}
